import { t } from 'i18next'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { FetchMeetingListItem } from '@/api/auditManager/interface'
import { MeetingCardWrap, WrapBG, WrapBody, WrapFooter, FileIcon } from './style'
import dayjs from 'dayjs'
import Icon from '@/components/Icon'
import { Utils } from '@/pages/index/ManageList/MeetingCard/utils'
import { Avatar } from '@/components/Avatar'
import { Trigger, Button, Modal } from '@kedacom/react-next'
import PopupUserWin from '@/pages/index/ManageList/MeetingCard/PopupUserWin'
import { useStore } from '../store'
import shallow from 'zustand/shallow'
import Docs, { DocsRef } from '@/pages/meetingList/MeetingCard/components/docs'
import Room from './room'
import { useGlobalStore } from '@/store/global'
import { getMeetingTime } from '@/utils'
import { WEEKDAY } from '@/plugins/dayjs'

export interface MeetingCardProps {
	className?: string
	entity: FetchMeetingListItem
	enable_upload?: boolean
	orderArr: [number, number]
	userMoid: string
}

const QT_MEETING = 'qtmeeting' //量子会议
const AES_MEETING = 'aesmeeting' //AES加密会议
const GM_MEETING = 'gmeeting' //国密加密会议

export function MeetingCard(props: MeetingCardProps) {
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const { update, auditOpt } = useStore(
		(state) => ({
			update: state.update,
			auditOpt: state.auditOpt,
		}),
		shallow
	)
	let { entity, className, enable_upload, orderArr, userMoid } = props
	const [fileNum, setFileNum] = useState(0)
	const FileManagerRef = useRef<DocsRef | null>(null)
	const [fileManagerOpen, setFileManagerOpen] = useState(false)
	const DETAIL_URL = './detail.html?meetingMoid=' + entity.meeting_id + '&audit'

	useEffect(() => {
		setFileNum(entity.file_num ?? 0)
	}, [entity.file_num])

	const meetingEncryptionType = useMemo(() => {
		//是会议类型
		if (entity.quantum_encryption === 1) {
			//量子
			return QT_MEETING
		} else if (entity.encrypted_type === 2) {
			return AES_MEETING
		} else if ((entity.encrypted_type === 3 || entity.encrypted_type === 4) && entity.quantum_encryption === 0) {
			return GM_MEETING
		}
		return ''
	}, [entity.quantum_encryption, entity.encrypted_type])

	const getSubject = (meeting: FetchMeetingListItem) => {
		let subject = meeting.name
		let prefix = ''
		if (meeting.super_mt_num) {
			prefix = t('[超大方]')
		}
		//6.1sp5已经去掉8方，默认都是192因此不再展示192方跟8方
		if (meeting.max_join_mt != 192) {
			prefix += '[' + t('{{num}}方', { num: meeting.max_join_mt ? meeting.max_join_mt : '192' }) + ']'
		}
		subject = prefix + subject
		return subject
	}

	const getRegularMeeting = (meeting: FetchMeetingListItem) => {
		const startDate = meeting.meeting_formular?.start_date ?? ''
		const endDate = meeting.meeting_formular?.end_date ?? ''
		return t('{{startDate}}开始，到{{endDate}}结束 ', { startDate: startDate, endDate: endDate })
	}
	//根据时长（分钟）获取对应的小时和分钟
	const getDuration = (duration: number) => {
		const _hour = parseInt((duration / 60).toString())
		return {
			hour: _hour,
			minute: duration - 60 * _hour,
		}
	}
	const getTextShow = (meeting: FetchMeetingListItem) => {
		const weekDayLabels = meeting.meeting_formular?.week_days
			? meeting.meeting_formular.week_days
					.split(',')
					.map((item) => WEEKDAY[Number(item)])
					.join(',')
			: ''
		const startTime = meeting.start_time ? dayjs(meeting.start_time).format('HH:mm') : ''
		const hour = getDuration(meeting.duration ?? 0).hour
		const minute = getDuration(meeting.duration ?? 0).minute
		let dateTime = t('每周的{{weekDayLabels}} {{startTime}}开始，', {
			weekDayLabels: weekDayLabels,
			startTime: startTime,
		})
		if (minute !== 0 && hour !== 0) {
			dateTime += t('时长{{hour}}小时{{minute}}分钟', {
				hour: hour,
				minute: minute,
				weekDayLabels: weekDayLabels,
				startTime: startTime,
			})
		} else if (hour !== 0) {
			dateTime += t('时长{{hour}}小时', { hour: hour })
		} else if (minute !== 0) {
			dateTime += t('时长{{minute}}分钟', { minute: minute })
		}
		return dateTime
	}
	const joinRooms = (rooms: Array<string>) => {
		let meetingRooms = ''
		if (rooms.length > 0) {
			for (var i = 0, length = rooms.length; i < length; i++) {
				meetingRooms += rooms[i] + '、'
			}
		}
		meetingRooms = Utils.code.encodeHTML(Utils.string.removeLastChar(meetingRooms))
		return meetingRooms
	}
	const getOrganizerInfo = (meeting: FetchMeetingListItem) => {
		let phone = ''
		const workPhoneNO = meeting.creator.telephone ?? ''
		const mobilePhone = meeting.creator.mobile ?? ''
		if (workPhoneNO && mobilePhone) {
			phone = `（${Utils.code.encodeHTML(workPhoneNO)}/${Utils.code.encodeHTML(mobilePhone)}）`
		} else if (workPhoneNO !== '' || mobilePhone !== '') {
			phone = '（' + (Utils.code.encodeHTML(workPhoneNO) || Utils.code.encodeHTML(mobilePhone)) + '）'
		}
		const organizerName = meeting.creator.name ?? ''
		return organizerName + phone
	}
	const rooms = joinRooms(entity.meeting_rooms ?? [])
	const title = getSubject(entity)
	const time = getMeetingTime(entity.start_time, entity.duration, entity.duration === 0)
	const openFile = () => {
		setFileManagerOpen(true)
	}
	return (
		<>
			<MeetingCardWrap className={className}>
				<WrapBG
					className={
						meetingEncryptionType === GM_MEETING
							? 'gm_meeting_bg'
							: meetingEncryptionType === AES_MEETING
							? 'aes_meeting_bg'
							: 'hidden'
					}
				></WrapBG>
				<WrapBody>
					<div className="main-left">
						<div className="meeting-card-body-line name">
							<a title={title} target="_blank" className="text" href={DETAIL_URL} rel="noreferrer">
								{title}
							</a>
						</div>
						<div className="meeting-card-body-line">
							{entity.duration === 0 ? (
								<span
									className={
										entity.is_attendee === 1 && entity.is_conflict === 1 ? 'conflict-time' : ''
									}
								>
									{time}
								</span>
							) : entity.regular_meeting_moid && entity.meeting_formular ? (
								<span>{getRegularMeeting(entity)}</span>
							) : entity.is_attendee === 1 && entity.is_conflict === 1 ? (
								<span className="conflict-time">{time}</span>
							) : (
								<span>{time}</span>
							)}
						</div>
						{entity.duration !== 0 && entity.regular_meeting_moid && entity.meeting_formular && (
							<div className="meeting-card-body-line">
								<span className="ellipsis regular">{getTextShow(entity)}</span>
							</div>
						)}
						{entity.meeting_rooms && entity.meeting_rooms.length > 0 && (
							<div className="meeting-card-body-line" key={Math.random()}>
								{entity.regular_meeting_moid && entity.meeting_formular ? (
									<Trigger
										popup={<Room key={entity.meeting_id} meeting={entity}></Room>}
										popupAlign={{ offset: [160, 0] }}
									>
										<span className="repeat-room-info">{t('会议室详情')}</span>
									</Trigger>
								) : (
									<span className="rooms">
										<span className="ellipsis room-names" title={rooms}>
											{rooms}
										</span>
										{rooms && entity.video && (
											<Trigger
												popup={<Room key={entity.meeting_id} meeting={entity}></Room>}
												popupAlign={{ offset: [160, 0] }}
											>
												<span className="video-room-info">{t('会议室详情')}</span>
											</Trigger>
										)}
									</span>
								)}
							</div>
						)}
						<div className="meeting-card-body-line">
							<div style={{ paddingRight: '4px', width: '100%' }}>{getOrganizerInfo(entity)}</div>
						</div>
						{enable_upload && !!SWITCH.fileManager && (
							<div
								className="meeting-card-body-line"
								style={{ height: '30px', alignItems: 'center' }}
								id={entity.meeting_id.toString()}
							>
								<span>{t('已上传{{fileNum}}个文档', { fileNum: fileNum })}</span>
								<FileIcon onClick={openFile} title={t('文件管理')}>
									<Icon></Icon>
								</FileIcon>
							</div>
						)}
					</div>
					<div className="fixed-right">
						<div className="fixed-right-line quantumEncryption-line" style={{ marginTop: '10px' }}>
							{meetingEncryptionType === QT_MEETING && (
								<Icon className="quantumEncryption qtmeeting " title={t('量子加密')}></Icon>
							)}
							{entity.regular_meeting_moid && entity.meeting_formular && (
								<Icon className="quantumEncryption rmeeting " title={t('例会')}></Icon>
							)}
							{meetingEncryptionType === GM_MEETING && (
								<Icon className="quantumEncryption gmeeting " title={t('国密加密')}></Icon>
							)}
							{meetingEncryptionType === AES_MEETING && (
								<Icon className="quantumEncryption aesmeeting " title={t('aes加密')}></Icon>
							)}
							{entity.cascade_meeting === 1 && (
								<Icon className="quantumEncryption cmeeting " title={t('级联会议')}></Icon>
							)}
							{entity.video === 1 && (
								<Icon className="quantumEncryption vmeeting " title={t('视频会议')}></Icon>
							)}
						</div>
						{entity.attending_person_num && (
							<div className="fixed-right-line">
								{t('共{{num}}位与会方', { num: entity.attending_person_num })}
							</div>
						)}
						<div className="fixed-right-line">
							{[...entity.members].slice(0, 3).map((mt, index) => {
								let user = {
									portrait: mt.portrait,
									accountType: mt.account_type,
								}
								return mt.account.length > 0 && !!SWITCH.userPopUp ? (
									<Trigger
										key={index}
										trigger="hover"
										popup={<PopupUserWin moid={mt.account} key={index}></PopupUserWin>}
										popupAlign={{
											points:
												orderArr[0] <= 1
													? orderArr[0] % 2 === 0
														? ['bl', 'tl']
														: ['br', 'tr']
													: orderArr[0] % 2 === 0
													? ['tl', 'bl']
													: ['tr', 'br'],
											offset:
												orderArr[0] <= 1
													? orderArr[0] % 2 === 0
														? [10, -20]
														: [-10, -20]
													: orderArr[0] % 2 === 0
													? [10, -5]
													: [-10, -5],
										}}
									>
										<div className="mt-each" key={index}>
											<div className="mt-each-header">
												<Avatar value={user}></Avatar>
											</div>
											<div className="mt-each-name">{mt.name}</div>
										</div>
									</Trigger>
								) : (
									<div className="mt-each" key={index}>
										<div className="mt-each-header">
											<Avatar value={user}></Avatar>
										</div>
										<div className="mt-each-name">{mt.name}</div>
									</div>
								)
							})}
						</div>
					</div>
				</WrapBody>
				<WrapFooter>
					<Button
						className="btn"
						onClick={() => {
							auditOpt({
								operation: 2,
								audit_by: userMoid,
								meeting_moid: entity.meeting_id,
							})
						}}
					>
						{t('批准')}
					</Button>
					<Button
						className="btn"
						onClick={() => {
							update({ cancelDialog: true, meetingMoid: entity.meeting_id })
						}}
					>
						{t('驳回')}
					</Button>
				</WrapFooter>
				{/* </div> */}
			</MeetingCardWrap>
			<Modal
				title={t('会议文档')}
				open={fileManagerOpen}
				width={848}
				height={508}
				okText={false}
				cancelText={false}
				footer={<></>}
				onCancel={() => {
					setFileManagerOpen(false)
					let number = FileManagerRef.current?.getFileNumber()
					setFileNum(number ?? 0)
				}}
			>
				<Docs
					ref={FileManagerRef}
					meetingInfo={{
						meetingMoid: props.entity.meeting_id,
						name: props.entity.name,
						e164: props.entity.conf_id,
						dateTime: '',
						isAudit: true,
					}}
				/>
			</Modal>
		</>
	)
}
